//
//  IdCardViewController.m
//  DanaKreditLoan
//
//  Created by ZhengChengFeng on 2024/10/21.
//

#import "IdCardViewController.h"
#import "IdCardFaceViewController.h"
#import "CustomCameraController.h"

#define kFootViewHeight  (15 + 48 + (IS_IPhoneX_All ? kHeight_BottomSafe : 15))

@interface IdCardViewController ()<CLLocationManagerDelegate>

@property (nonatomic) UIImageView *cardImgView;
@property (nonatomic) UITextFieldHelper *fullNameFiled,*IDNoFiled,*DateFiled;

@property (nonatomic) NSString *nameStr,*idNoStr,*dateStr;

@property (nonatomic) NSString *startTimeStr,*endTimeStr;
@property (nonatomic) CLLocationManager *locationManager;
@property (nonatomic) NSTimer *timer;
@property (nonatomic) NSInteger timeInt;
@property (nonatomic) BOOL isLocationSuccess;

@end

@implementation IdCardViewController

- (void)back{
    [[DKCore sharedDKCore] jumpWLAlertView:^{
        [[self getCurrentVC] jumpToPopControlClass:@"OrderDetailViewController"];
    }];
}

- (void)initFootView{

    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kFootViewHeight - kNavigationBarHeight, kScreenWidth, kFootViewHeight)];
    bottomV.backgroundColor = kTableViewBackColor;
    [self.view addSubview:bottomV];
    
    
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 15, kScreenWidth - 30, 48)];
    nextBtn.titleLabel.font = [UIFont fontWithName:kFuturaMedium size:16];
    [nextBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [nextBtn setTitleColor:kWhiteColor forState:UIControlStateSelected];
    [nextBtn setTitleColor:kWhiteColor forState:UIControlStateHighlighted];
    [nextBtn setTitle:ASLocalizedString(@"Next Step") forState:UIControlStateNormal];
    [nextBtn setTitle:ASLocalizedString(@"Next Step") forState:UIControlStateSelected];
    [nextBtn setTitle:ASLocalizedString(@"Next Step") forState:UIControlStateHighlighted];
    [nextBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateNormal];
    [nextBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateSelected];
    [nextBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateHighlighted];
    [nextBtn addTarget:self action:@selector(clickAlbum) forControlEvents:UIControlEventTouchUpInside];
    nextBtn.backgroundColor = kButtonDefaultColor;
    nextBtn.layer.cornerRadius = 24;
    nextBtn.layer.masksToBounds = YES;
    [bottomV addSubview:nextBtn];
    [nextBtn setImgRightTitltLeft:10];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kFootViewHeight );
    
    [self initFootView];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(53 + 118 + 53 + 268 + 15 + 309))];
    self.tableView.tableHeaderView = headView;
    
    UIImageView *imgV1 = [[UIImageView alloc] initWithFrame:CGRectMake(20, DimensionBaseIphone6(53), kScreenWidth - 40, DimensionBaseIphone6(118))];
    imgV1.image = [UIImage imageNamed:@"icon_idcard1"];
    [headView addSubview:imgV1];
    
    UIImageView *imgV2 = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - DimensionBaseIphone6(174))/2, DimensionBaseIphone6(20), DimensionBaseIphone6(174), DimensionBaseIphone6(176))];
    imgV2.image = [UIImage imageNamed:@"icon_idcard2"];
    [headView addSubview:imgV2];
    
    
    UIView *backV1 = [[UIView alloc] initWithFrame:CGRectMake(15, imgV1.bottom + DimensionBaseIphone6(53), kScreenWidth - 30, DimensionBaseIphone6(268))];
    backV1.backgroundColor = [UIColor whiteColor];
    [headView addSubview:backV1];
    backV1.layer.cornerRadius = 14;
    backV1.layer.masksToBounds = YES;
    
    
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake((backV1.width - 48)/2+24, DimensionBaseIphone6(25), (backV1.width - 48)/2, DimensionBaseIphone6(8))];
    line2.backgroundColor = kBlackColor;
    [backV1 addSubview:line2];
    line2.layer.cornerRadius = DimensionBaseIphone6(4);
    line2.layer.masksToBounds = YES;
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(24, DimensionBaseIphone6(25), (backV1.width - 48)/2 + 2, DimensionBaseIphone6(8))];
    line1.backgroundColor = [UIColor colorWithHexString:@"#75FA8D"];
    [backV1 addSubview:line1];
    line1.layer.cornerRadius = DimensionBaseIphone6(4);
    line1.layer.masksToBounds = YES;
    
    UIImageView *lineV1 = [[UIImageView alloc] initWithFrame:CGRectMake(24 + (line1.width -11)/2 , line1.top - 1.5, 11, 11)];
    [backV1 addSubview:lineV1];
    lineV1.image = [UIImage imageNamed:@"icon_idcard3"];
    
    UIImageView *lineV2 = [[UIImageView alloc] initWithFrame:CGRectMake(line1.right + (line2.width-11)/2 , lineV1.top, 11, 11)];
    [backV1 addSubview:lineV2];
    lineV2.image = [UIImage imageNamed:@"icon_idcard4"];
    
    UILabel *lab1 = [UILabel createLabel:[UIFont fontWithName:kFutura size:13] color:[UIColor colorWithHexString:@"#03241B"]];
    lab1.text = ASLocalizedString(@"Aadhaar Front");
    [backV1 addSubview:lab1];
    lab1.textAlignment = 1;
    lab1.frame = CGRectMake(line1.left, lineV1.bottom, line1.width, DimensionBaseIphone6(20));
    
    UILabel *lab2 = [UILabel createLabel:[UIFont fontWithName:kFutura size:13] color:[UIColor colorWithHexString:@"#03241B"]];
    lab2.text = ASLocalizedString(@"Face");
    [backV1 addSubview:lab2];
    lab2.textAlignment = 1;
    lab2.frame = CGRectMake(line2.left, lineV2.bottom, line2.width, DimensionBaseIphone6(20));
    

    UIImageView *imgV3 = [[UIImageView alloc] initWithFrame:CGRectMake(backV1.width - 4 - 97, backV1.height - DimensionBaseIphone6(62) - 2, 97, DimensionBaseIphone6(62))];
    imgV3.image = [UIImage imageNamed:@"icon_idcard5"];
    [backV1 addSubview:imgV3];
    
    
    UIImageView *imgV4 = [[UIImageView alloc] initWithFrame:CGRectMake((backV1.width - 248)/2, DimensionBaseIphone6(89), 248, DimensionBaseIphone6(155))];
    imgV4.image = [UIImage imageNamed:@"icon_idcard6"];
    [backV1 addSubview:imgV4];
    

    UIImageView *imgV5 = [[UIImageView alloc] initWithFrame:CGRectMake((imgV4.width - DimensionBaseIphone6(45))/2, (imgV4.height - DimensionBaseIphone6(45))/2, DimensionBaseIphone6(45), DimensionBaseIphone6(45))];
    imgV5.image = [UIImage imageNamed:@"icon_idcard7"];
    [imgV4 addSubview:imgV5];
    
    
    backV1.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAlbum)];
    [backV1 addGestureRecognizer:tap];
    
    
    UIView *backV2 = [[UIView alloc] initWithFrame:CGRectMake(15, backV1.bottom + DimensionBaseIphone6(15), kScreenWidth - 30, DimensionBaseIphone6(309))];
    backV2.backgroundColor = [UIColor whiteColor];
    [headView addSubview:backV2];
    backV2.layer.cornerRadius = 14;
    backV2.layer.masksToBounds = YES;
    
    
    UIView *nameV = [[UIView alloc] initWithFrame:CGRectMake(15, DimensionBaseIphone6(15), backV2.width - 30, DimensionBaseIphone6(83))];
    nameV.backgroundColor = [UIColor whiteColor];
    [backV2 addSubview:nameV];
    nameV.layer.cornerRadius = 14;
    nameV.layer.masksToBounds = YES;
    nameV.layer.borderColor = [UIColor colorWithHexString:@"#EFEFEF"].CGColor;
    nameV.layer.borderWidth = 1;
    
    UILabel *labName = [UILabel createLabel:[UIFont fontWithName:kFutura size:14] color:[UIColor colorWithHexString:@"#6C6C6C"]];
    labName.text = ASLocalizedString(@"Aadhaar Name");
    [nameV addSubview:labName];
    labName.frame = CGRectMake(15, DimensionBaseIphone6(15), 200, DimensionBaseIphone6(20));
    
    self.fullNameFiled = [[UITextFieldHelper alloc] initWithFrame:CGRectMake(labName.left, labName.bottom,nameV.width - 30, DimensionBaseIphone6(45))];
    [nameV addSubview:self.fullNameFiled];
    self.fullNameFiled.textColor = kBlackColor;
    self.fullNameFiled.font = [UIFont fontWithName:kFuturaBT size:14];
    self.fullNameFiled.userInteractionEnabled = NO;
    
    
    UIView *numberV = [[UIView alloc] initWithFrame:CGRectMake(15,nameV.bottom + DimensionBaseIphone6(15), backV2.width - 30, DimensionBaseIphone6(83))];
    numberV.backgroundColor = [UIColor whiteColor];
    [backV2 addSubview:numberV];
    numberV.layer.cornerRadius = 14;
    numberV.layer.masksToBounds = YES;
    numberV.layer.borderColor = [UIColor colorWithHexString:@"#EFEFEF"].CGColor;
    numberV.layer.borderWidth = 1;
    
    UILabel *labNumber = [UILabel createLabel:[UIFont fontWithName:kFutura size:14] color:[UIColor colorWithHexString:@"#6C6C6C"]];
    labNumber.text = ASLocalizedString(@"Aadhaar Number");
    [numberV addSubview:labNumber];
    labNumber.frame = CGRectMake(15, DimensionBaseIphone6(15), 200, DimensionBaseIphone6(20));
    
    self.IDNoFiled = [[UITextFieldHelper alloc] initWithFrame:CGRectMake(labNumber.left, labNumber.bottom,numberV.width - 30, DimensionBaseIphone6(45))];
    [numberV addSubview:self.IDNoFiled];
    self.IDNoFiled.textColor = kBlackColor;
    self.IDNoFiled.font = [UIFont fontWithName:kFuturaBT size:14];
    self.IDNoFiled.userInteractionEnabled = NO;
    self.IDNoFiled.keyboardType = UIKeyboardTypeNumberPad;
    
    
    
    UIView *dateV = [[UIView alloc] initWithFrame:CGRectMake(15,numberV.bottom + DimensionBaseIphone6(15), backV2.width - 30, DimensionBaseIphone6(83))];
    dateV.backgroundColor = [UIColor whiteColor];
    [backV2 addSubview:dateV];
    dateV.layer.cornerRadius = 14;
    dateV.layer.masksToBounds = YES;
    dateV.layer.borderColor = [UIColor colorWithHexString:@"#EFEFEF"].CGColor;
    dateV.layer.borderWidth = 1;
    
    UILabel *labDate = [UILabel createLabel:[UIFont fontWithName:kFutura size:14] color:[UIColor colorWithHexString:@"#6C6C6C"]];
    labDate.text = ASLocalizedString(@"Birthday");
    [dateV addSubview:labDate];
    labDate.frame = CGRectMake(15, DimensionBaseIphone6(15), 200, DimensionBaseIphone6(20));
    
    self.DateFiled = [[UITextFieldHelper alloc] initWithFrame:CGRectMake(labDate.left, labDate.bottom,dateV.width - 30, DimensionBaseIphone6(45))];
    [dateV addSubview:self.DateFiled];
    self.DateFiled.textColor = kBlackColor;
    self.DateFiled.font = [UIFont fontWithName:kFuturaBT size:14];
    self.DateFiled.userInteractionEnabled = NO;
    self.DateFiled.keyboardType = UIKeyboardTypeNumberPad;
    
    
    UIImageView *rightImgV = [[UIImageView alloc] initWithFrame:CGRectMake(dateV.frame.size.width - 15 - 11, 0, 11, 8)];
    rightImgV.centerY = self.DateFiled.centerY;
    [dateV addSubview:rightImgV];
    rightImgV.image = [UIImage imageNamed:@"icon_idcard8"];
    
    
    UIView *shadeV1 = [[UIView alloc] initWithFrame:self.fullNameFiled.frame];
    shadeV1.userInteractionEnabled = YES;
    shadeV1.backgroundColor = [UIColor clearColor];
    [nameV addSubview:shadeV1];
    
    UIView *shadeV2 = [[UIView alloc] initWithFrame:self.IDNoFiled.frame];
    shadeV2.userInteractionEnabled = YES;
    shadeV2.backgroundColor = [UIColor clearColor];
    [numberV addSubview:shadeV2];
    
    UIView *shadeV3 = [[UIView alloc] initWithFrame:self.DateFiled.frame];
    shadeV3.userInteractionEnabled = YES;
    shadeV3.backgroundColor = [UIColor clearColor];
    [dateV addSubview:shadeV3];
    
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAlbum)];
    [shadeV1 addGestureRecognizer:tap1];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAlbum)];
    [shadeV2 addGestureRecognizer:tap2];
    
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAlbum)];
    [shadeV3 addGestureRecognizer:tap3];
    
}

- (void)clickAlbum{
    
    AlertPhotoGuideView *alertV = [[AlertPhotoGuideView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withFace:NO];
    [[UIApplication sharedApplication].keyWindow addSubview:alertV];
    alertV.clickSureBlock = ^{
        [self goPhoto];
    };
    
    
}

- (void)goPhoto{

    [AuthorHelper isCanUseCamera:^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.startTimeStr = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
            CustomCameraController *vc = [[CustomCameraController alloc] init];
            UINavigationController *naV = [[UINavigationController alloc]initWithRootViewController:vc];
            naV.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self presentViewController:naV animated:YES completion:nil];
            
            vc.callBackPhotoData = ^(NSData * _Nonnull imgData) {
                [self uploadPicture:@"2" withImgData:imgData];
            };
        });
        
        
        
    }];
    

}

- (void)uploadPicture:(NSString *)sneering withImgData:(id)data{
    
    NSData *imgData = data;
        
    NSMutableDictionary *muDic = @{
        @"cultivate":@"2",
        @"lord":@"11",
        @"blankets":@"",
        @"colony":@"",
    }.mutableCopy;
    
    if ([CurrentUser mine].isYNLanguage) {
        muDic = @{
            @"lord":@"11",
            @"cultivate":@"2",
            @"colony":@"",
            @"amazing":@"1",
            @"set":@"setPic",
        }.mutableCopy;
    }
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    [HttpNetHelper postUploadPhotoUrl:kUploadPicUrl params:muDic imageData:imgData name:@"boring" fileName:@"fileName.jpg" mimeType:@"image/jpeg" withProgress:^(double pro) {
        
    } success:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        NSDictionary *dic = responseDic[@"clip"];
        AlertPhotoDataView *picker = [[AlertPhotoDataView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        
        [picker pickViewWithNameStr:esString(dic[@"hydrogen"]) andIDNoStr:esString(dic[@"shyly"]) andDateStr:esString(dic[@"flattered"])];
        
        [[UIApplication sharedApplication].keyWindow addSubview:picker];
        [picker showBottomView];
        
        
        picker.callBackInfoStr = ^(NSString * _Nonnull nameStr, NSString * _Nonnull idNoStr, NSString * _Nonnull dateStr) {
//            self.fullNameFiled.text = esString(nameStr);
//            self.IDNoFiled.text = esString(idNoStr);
//            self.DateFiled.text = esString(dateStr);
            
            self.nameStr = esString(nameStr);
            self.idNoStr = esString(idNoStr);
            self.dateStr = esString(dateStr);
            [self goNextPage];
        };
        
        
        
    } failure:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
    }];
    
}

- (void)goNextPage{
    
    NSMutableDictionary *muDic = @{
        @"hydrogen":esString(self.nameStr),
        @"shyly":esString(self.idNoStr),
        @"flattered":esString(self.dateStr),
        @"estuary":@"estuaryIdCard",
        @"lord":@"11",
    }.mutableCopy;
    if ([CurrentUser mine].isYNLanguage) {
        muDic = @{
            @"hydrogen":esString(self.nameStr),
            @"shyly":esString(self.idNoStr),
            @"flattered":esString(self.dateStr),
            @"healthfuller":@"healthfullerIdCard",
            @"developed":@"developedIdCard",
            @"largely":esString(self.idStr),
            @"quinine":esString([[NSUserDefaults standardUserDefaults] objectForKey:kUserTelPhone]),
            @"dosed":esString(self.orderNoStr),
        }.mutableCopy;
    }
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    [HttpNetHelper postNetworkHelperForPath:[CurrentUser mine].isYNLanguage ? kSaveIdIdentifyYNUrl : kSaveIdIdentifyYDUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
                return;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationHideAlertView object:nil];
        
        self.endTimeStr = esString([NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"]);
        [self uploadMaiDianIdCardData];
        
        IdCardFaceViewController *vc = [[IdCardFaceViewController alloc] init];
        vc.idStr = esString(self.idStr);
        vc.orderNoStr = esString(self.orderNoStr);
        vc.title = self.title;
        [self.navigationController pushViewController:vc animated:YES];
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
    } withIsForm:YES];
    
    
}

#pragma mark -------   uploadMaiDianIdCardData  -------
- (void)uploadMaiDianIdCardData{
    self.timeInt = 0;
    self.isLocationSuccess = NO;
    [self initLocation];
}

- (void)initLocation{
    
    self.timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(addTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestLocation];
}

- (void)addTimer{
    self.timeInt ++;
    if (self.isLocationSuccess) {
        [self.timer invalidate];
        self.timer = nil;
        self.timeInt = 0;
    }
    else{
        if (self.timeInt > 8) {
            [self.timer invalidate];
            self.timer = nil;
            self.timeInt = 0;
            NSString *longitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLongitude];
            NSString *latitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLatitude];
            
            [self goServerWithLongitudeStr:PMStringIsEmpty(longitudeStr) ? @"" : longitudeStr withLatitudeStr:PMStringIsEmpty(latitudeStr) ? @"" : latitudeStr];
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *newlocation = locations[0];
    NSString *longitudeStr = [NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude];
    NSString *latitudeStr =  [NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude];
    [self.locationManager stopUpdatingLocation];
    
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude] forKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude] forKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.isLocationSuccess = YES;
    
    if (self.timeInt <= 8) {
        [self goServerWithLongitudeStr:esString(longitudeStr) withLatitudeStr:esString(latitudeStr)];
    }
    

}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}

- (void)goServerWithLongitudeStr:(NSString *)longitudeStr withLatitudeStr:(NSString *)latitudeStr{

    [DataCategoryUpload uploadMaiDianData:@"2" withOrderIdStr:esString(self.idStr) withOrderNoStr:esString(self.orderNoStr) withLongitude:esString(longitudeStr) withLatitude:esString(latitudeStr) withStartTime:self.startTimeStr withEndTime:self.endTimeStr];

}




@end
